<?php
    /*
    * Copyright (c) 2007, Osuvaldo Ramos
    * 
    * All rights reserved.
    * 
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are
    * met:
    *
    *    * Redistributions of source code must retain the above copyright
    *      notice, this list of conditions and the following disclaimer.
    *    * Redistributions in binary form must reproduce the above copyright
    *      notice, this list of conditions and the following disclaimer in the
    *      documentation and/or other materials provided with the distribution.
    *    * Neither the name of the CoreTech nor the names of its
    *      contributors may be used to endorse or promote products derived from
    *      this software without specific prior written permission.
    * 
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
    * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    * 
    * $Id: default.php 2 2008-01-21 02:48:28Z xdracox $
    */
    
    if ( !defined('BNETCS') || !defined('ROOT') ) exit();
    
    // define the ranks
    define('RANK_TRAINEE',             1);
    define('RANK_PRIVATE',             2);
    define('RANK_PRIVATE_FIRST_CLASS', 3);
    define('RANK_CORPORAL',            4);
    define('RANK_SERGEANT',            5);
    define('RANK_STAFF_SERGEANT',      6);
    define('RANK_SERGEANT_FIRST_CLASS',7);
    define('RANK_MASTER_SERGEANT',     8);
    define('RANK_SECOND_LIEUTENANT',   9);
    define('RANK_FIRST_LIEUTENANT',    10);
    define('RANK_CAPTAIN',             11);
    define('RANK_MAJOR',               12);
    define('RANK_LIEUTENANT_COLONEL',  13);
    define('RANK_COLONEL',             14);
    define('RANK_BRIGADIER_GENERAL',   15);
    define('RANK_MAJOR_GENERAL',       16);
    define('RANK_LIEUTENANT_GENERAL',  17);
    define('RANK_GENERAL',             18);
    define('RANK_COMMANDER',           19);
    
    class RankSystem
    {
        var $smarty;
        
        function RankSystem()
        {
            $this->smarty = new Smarty();
            $this->smarty->template_dir = ROOT.'/mods/RankSystem/default';
            $this->smarty->compile_dir = $this->smarty->template_dir;
        }
        
        function displayRanks()
        {
            global $mdb2;
            
            $all_ranks = array();
            
            $sql = 'SELECT *
                FROM bnetcs_defaultrs_rank_categories
                ORDER BY rank_category_level
                    DESC';
            $cat_result = $mdb2->query($sql);
            
            while ( $cat_row = $cat_result->fetchRow() )
            {
                $cat_id = $cat_row['rank_category_id'];
                
                $sql = sprintf('SELECT *
                    FROM bnetcs_defaultrs_ranks
                    WHERE rank_category_id = %d
                    ORDER BY rank_level
                        DESC', $cat_id);
                $rank_result = $mdb2->query($sql);
                
                $ranks = array();
                
                while ( $rank_row = $rank_result->fetchRow() )
                {
                    $ranks[] = array
                    (
                        'img' => $rank_row['rank_image'],
                        'name' => $rank_row['rank_name'],
                        'description' => $rank_row['rank_description']
                    );
                }
                
                $all_ranks[] = array
                (
                    'name' => $cat_row['rank_category_name'],
                    'ranks' => $ranks
                );
            }
            
            $this->smarty->assign('site_root', '.');
            $this->smarty->assign('ranks', $all_ranks);
            $this->smarty->display('rankpage.tpl');
        }
        
        function displayConsole()
        {
            
        }
        
        function canRecruit($member_id)
        {
            return $this->getRank($member_id) >= RANK_SECOND_LIEUTENANT;
        }
        
        function getRank($member_id)
        {
            global $mdb2;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_member_ranks
                WHERE member_id = %d', $member_id);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            $rank_id = $row['rank_id'];
            
            $sql = sprintf('SELECT rank_level
                FROM bnetcs_defaultrs_ranks
                WHERE rank_id = %d', $rank_id);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            return $row['rank_level'];
        }
        
        function getRankName($mid)
        {
            global $mdb2;
            
            $level = $this->getRank($mid);
            
            $sql = sprintf('SELECT rank_name
                FROM bnetcs_defaultrs_ranks
                WHERE rank_level = %d', $level);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'MySQL query failed: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            
            $row = $result->fetchRow();
            
            return $row['rank_name'];
        }
        
        function getAllRanks($max_rank = RANK_COMMANDER)
        {
            global $mdb2;
            
            $sql = sprintf('SELECT *
                FROM bnetcs_defaultrs_ranks
                WHERE rank_level < %d
                ORDER BY rank_level
                    ASC', $max_rank);
            $result = $mdb2->query($sql);
            $all_ranks = array();
            
            while ( $row = $result->fetchRow() )
            {
                $all_ranks[] = array
                (
                    'id' => $row['rank_id'],
                    'level' => $row['rank_level'],
                    'name' => $row['rank_name'],
                    'description' => $row['rank_description']
                );
            }
            
            return $all_ranks;
        }
        
        function getRankImgDir()
        {
            return ROOT.'/mods/RankSystem/default/img';
        }
        
        function canPromote($mid)
        {
            return $this->getRank($mid) >= RANK_SECOND_LIEUTENANT;
        }
        
        function canDemote($mid)
        {
            return $this->getRank($mid) >= RANK_BRIGADIER_GENERAL;
        }
        
        function onLogin($mid)
        {
            global $mdb2;
            
            $oldrank = $this->getRank($mid);
            $newrank = $oldrank;
            
            $sql = sprintf('SELECT member_join_date
                FROM bnetcs_members
                WHERE member_id = %d', $mid);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'MySQL query failed: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            
            $row = $result->fetchRow();
            
            $join_date = $row['member_join_date'];
            $now = time();
            $span = $now - $join_date;
            
            $next_rank_lvl = $this->getRank($mid) + 1;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_ranks
                WHERE rank_level = %d', $next_rank_lvl);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'MySQL query failed: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            $row = $result->fetchRow();
            
            $next_rank_id = $row['rank_id'];
            
            if ( $oldrank < RANK_SERGEANT )
            {
                switch ( $oldrank )
                {
                    case RANK_TRAINEE:
                    {
                        if ( $span >= WEEK )
                            $this->setRank($mid, $next_rank_id);
                        break;
                    }
                    case RANK_PRIVATE:
                    {
                        if ( $span >= 4 * WEEK )
                            $this->setRank($mid, $next_rank_id);
                        break;
                    }
                    case RANK_PRIVATE_FIRST_CLASS:
                    {
                        if ( $span >= 8 * WEEK )
                            $this->setRank($mid, $next_rank_id);
                        break;
                    }
                    case RANK_CORPORAL:
                    {
                        if ( $span >= 12 * WEEK )
                            $this->setRank($mid, $next_rank_id);
                        break;
                    }
                }
            }
        }
        
        function addUser($member_id, $first_member = false)
        {
            global $mdb2;
            
            $rank = $first_member ? RANK_COMMANDER : RANK_TRAINEE;
            
            $sql = sprintf('INSERT
                INTO bnetcs_defaultrs_member_ranks (rank_id, member_id)
                VALUES (%d, %d)', $rank, $member_id);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'MySQL query failed: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
        }
        
        function maxPromotionRank($mid)
        {
            global $mdb2;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_member_ranks
                WHERE member_id = %d', $mid);
            $rid_result = $mdb2->query($sql);
            
            if ( PEAR::isError($rid_result) )
            {
                $msg = 'MySQL query failed: '.$rid_result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            
            $rid_row = $rid_result->fetchRow();
            
            $sql = sprintf('SELECT rank_level
                FROM bnetcs_defaultrs_ranks
                WHERE rank_id = %d', $rid_row['rank_id']);
            $lvl_result = $mdb2->query($sql);
            $lvl_row = $lvl_result->fetchRow();
            $level = $lvl_row['rank_level'];
            
            switch ( $level )
            {
                case RANK_COMMANDER:
                {
                    return RANK_COMMANDER - 1;
                }
                default:
                {
                    return $level - 4;
                }
            }
        }
        
        function maxDemotionRank($mid)
        {
            global $mdb2;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_member_ranks
                WHERE member_id = %d', $mid);
            $rid_result = $mdb2->query($sql);
            
            if ( PEAR::isError($rid_result) )
            {
                $msg = 'MySQL query failed: '.$rid_result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            
            $rid_row = $rid_result->fetchRow();
            $rank_id = $rid_row['rank_id'];
            
            $sql = sprintf('SELECT rank_level
                FROM bnetcs_defaultrs_ranks
                WHERE rank_id = %d', $rank_id);
            $lvl_result = $mdb2->query($sql);
            
            if ( PEAR::isError($lvl_result) )
            {
                $msg = 'MySQL query failed: '.$lvl_result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            
            $lvl_row = $lvl_result->fetchRow();
            $level = $lvl_row['rank_level'];
            
            switch ( $level )
            {
                case RANK_COMMANDER:
                    return RANK_COMMANDER - 1;
                default:
                    return $level - 4;
            }
        }
        
        function givePromotion($mid)
        {
            global $mdb2;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_member_ranks
                WHERE member_id = %d', $mid);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            $rank_id = $row['rank_id'];
            
            $sql = sprintf('SELECT rank_level
                FROM bnetcs_defaultrs_ranks
                WHERE rank_id = %d', $rank_id);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            $level = $row['rank_level'];
            $level++;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_ranks
                WHERE rank_level = %d', $level);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            $new_rank_id = $row['rank_id'];
            
            $sql = sprintf('UPDATE bnetcs_defaultrs_member_ranks
                SET rank_id = %d
                WHERE member_id = %d', $new_rank_id, $mid);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'Failed to promote member: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
        }
        
        function giveDemotion($mid)
        {
            global $mdb2;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_member_ranks
                WHERE member_id = %d', $mid);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            $rank_id = $row['rank_id'];
            
            $sql = sprintf('SELECT rank_level
                FROM bnetcs_defaultrs_ranks
                WHERE rank_id = %d', $rank_id);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            $level = $row['rank_level'];
            $level--;
            
            $sql = sprintf('SELECT rank_id
                FROM bnetcs_defaultrs_ranks
                WHERE rank_level = %d', $level);
            $result = $mdb2->query($sql);
            $row = $result->fetchRow();
            
            $new_rank_id = $row['rank_id'];
            
            $sql = sprintf('UPDATE bnetcs_defaultrs_member_ranks
                SET rank_id = %d
                WHERE member_id = %d', $new_rank_id, $mid);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'Failed to promote member: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
        }
        
        function getMembersWithRank($rank_id)
        {
            global $mdb2;
            
            $sql = sprintf('SELECT member_id
                FROM bnetcs_defaultrs_member_ranks
                WHERE rank_id = %d', $rank_id);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'MySQL query failed: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            
            $members = array();
            
            while ( $row = $result->fetchRow() )
            {
                $sql = sprintf('SELECT *
                    FROM bnetcs_members
                    WHERE member_id = %d', $row['member_id']);
                $member_result = $mdb2->query($sql);
                
                if ( PEAR::isError($member_result) )
                {
                    $msg = 'MySQL query failed: '.$member_result->getMessage();
                    trigger_error($msg, E_USER_ERROR);
                }
                
                $member_row = $member_result->fetchRow();
                
                $sql = sprintf('SELECT rank_name
                    FROM bnetcs_defaultrs_ranks
                    WHERE rank_id = %d', $rank_id);
                $rank_result = $mdb2->query($sql);
                
                if ( PEAR::isError($rank_result) )
                {
                    $msg = 'MySQL query failed: '.$rank_result->getMessage();
                    trigger_error($msg, E_USER_ERROR);
                }
                
                $rank_row = $rank_result->fetchRow();
                
                $members[] = array
                (
                    'id' => $member_row['member_id'],
                    'name' => $member_row['member_login'],
                    'rank' => $rank_row['rank_name']
                );
            }
            
            return $members;
        }
        
        function setRank($mid, $rank_id)
        {
            global $mdb2;
            
            $sql = sprintf('UPDATE bnetcs_defaultrs_member_ranks
                SET rank_id = %d 
                WHERE member_id = %d', $rank_id, $mid);
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'MySQL query failed: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
        }
    }
?>
